package com.company.common.util;
//import com.example.common.util.RandomCodeUtil;

import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class SendMessageUtil {
    public static Boolean SendEmail(String qqRecipient,String code6) {
        try {
            //创建一个配置文件并保存
            Properties properties = new Properties();
            properties.setProperty("mail.host", "smtp.qq.com");
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.auth", "true");
            //QQ存在一个特性设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            //创建一个session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1579321143@qq.com", "jhpgufkvyxdahhhj");
                }
            });
            //获取连接对象
            Transport transport = session.getTransport();
            //连接服务器
            transport.connect("smtp.qq.com", "1579321143@qq.com", "jhpgufkvyxdahhhj");
            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);
            //邮件发送人
            mimeMessage.setFrom(new InternetAddress("1579321143@qq.com"));
            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(qqRecipient));
            //邮件标题
            mimeMessage.setSubject("Hello Mail");
            System.out.println("发送的验证码为-------------"+code6);
            //邮件内容
            mimeMessage.setContent(CodeFormatUtil.emailFormat("欢迎注册","新用户",code6,"注册登入"), "text/html;charset=UTF-8");
            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            //关闭连接
            transport.close();
        } catch (GeneralSecurityException | MessagingException e) {
            e.printStackTrace();
        }
        return true;
    }
}
